package com.sy.simpleegg.base

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Process
import android.view.MotionEvent
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.viewbinding.ViewBinding
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.util.BoardApiUtil
import com.sy.simpleegg.util.DateTimeUtil
import com.sy.simpleegg.util.GsonUtil
import com.sy.simpleegg.util.SoftInputUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import java.util.Random


abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {

    private var lastClickTime = 0L

    private var _binding: VB? = null
    val binding get() = _binding!!

    private val activityManager: ActivityManager by lazy { getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager }

    private var locationManager: LocationManager? = null
    private var locationProvider: String? = null
    private var longitude: String? = null//经度
    private var latitude: String? = null//纬度

    private var assisReceiver: AssisReceiver? = null

    abstract fun getViewBinding(): VB

    /**
     * 布局文件id
     */
    abstract fun attachLayoutRes(): Int

    abstract fun initData()

    abstract fun initView()

    abstract fun initOther()

    open fun useEventBus(): Boolean = true

    override fun onCreate(savedInstanceState: Bundle?) {
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        super.onCreate(savedInstanceState)
        _binding = getViewBinding()
//        setContentView(attachLayoutRes())
        setContentView(_binding?.root)
        if (useEventBus()) {
            EventBus.getDefault().register(this)
        }

        BoardApiUtil.keepAlive()
        BoardApiUtil.setBar(false, this)

        initData()
        initView()
        initOther()
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_UP) {
            val v = currentFocus
            //如果点击坐标不在EditText区域，则关闭软键盘
            if (SoftInputUtil.isHideKeyboard(v, ev)) {
                SoftInputUtil.hideSoftInput(v)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    override fun onDestroy() {
        super.onDestroy()
        unRegist()
        if (useEventBus()) {
            EventBus.getDefault().unregister(this)
        }
    }

    fun isHandlingData(): Boolean {
        val currentClickTime = System.currentTimeMillis()
        val canClick = currentClickTime - lastClickTime > Constant.RECEIVED_INTERVAL
        lastClickTime = currentClickTime
        return canClick
    }

    fun exit() {
        BoardApiUtil.setBar(true, this)
        BoardApiUtil.cancelKeepAlive()
        finishAndRemoveTask()
        Process.killProcess(Process.myPid())
    }

//    @SuppressLint("MissingPermission")
//    fun initLocation(){
//        locationManager = baseContext.getSystemService(Context.LOCATION_SERVICE) as LocaleManager
//
//        locationManager?.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000L, 0F, object : LocationListener{
//            override fun onLocationChanged(location: Location) {
//                TODO("Not yet implemented")
//            }
//        })
//    }

    @SuppressLint("MissingPermission")
    fun initLocation() {
        //1.获取位置管理器
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

        //2.获取位置提供器，GPS或是NetWork
        val providers = locationManager!!.getProviders(true)
        logFile(" ：${GsonUtil.getInstance()?.toJson(providers)}")
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER
            logFile("定位方式GPS")
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER
            logFile("定位方式Network")
        } else {
            logFile("没有可用的位置提供器")
            return
        }

        locationProvider?.let {
            //获取上次的位置，一般第一次运行，此值为null
            locationManager!!.getLastKnownLocation(it)?.let { location ->
                logFile("上一次位置-经纬度：" + location.longitude + "   " + location.latitude)
                longitude = location.longitude.toString()
                latitude = location.latitude.toString()
            }

            //监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
            locationManager?.requestLocationUpdates(
                locationProvider!!,
                3000L,
                1F,
                object : LocationListener {
                    // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
                    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
                        logFile("位置监视Provider状态变化：provider=$provider status=$status extras=$extras")
                    }

                    // Provider被enable时触发此函数，比如GPS被打开
                    override fun onProviderEnabled(provider: String) {
                        logFile("位置监视Provider打开：provider=$provider")
                    }

                    // Provider被disable时触发此函数，比如GPS被关闭
                    override fun onProviderDisabled(provider: String) {
                        logFile("位置监视Provider关闭：provider=$provider")
                    }

                    //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
                    override fun onLocationChanged(location: Location) {
                        logFile("监视地理位置变化-经纬度：" + location.longitude + "   " + location.latitude)
                        longitude = location.longitude.toString()
                        latitude = location.latitude.toString()
                    }
                })
        }
    }

    fun delayToReboot(delaySecond: Int){
        lifecycleScope.launch {
            delay(delaySecond*1000L)
            rebootDaily()
        }
    }

    open fun rebootDaily(){

    }

    fun registReceiver(){
        assisReceiver = AssisReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(Intent.ACTION_TIME_TICK)
        registerReceiver(assisReceiver, intentFilter)
    }

    private fun unRegist(){
        assisReceiver?.let {
            unregisterReceiver(it)
        }
    }

    inner class AssisReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                Intent.ACTION_TIME_TICK -> {
                    val rebootTime: String = DateTimeUtil.dateHHmm
                    if (rebootTime == Constant.REBOOT_TIME) {
                        //随机延迟60-599秒重启
                        val random = Random()
                        val delay = random.nextInt(539) + 60
                        logFile("延迟 $delay 秒重启系统")
                        delayToReboot(delay)
                    }
                }
            }
        }
    }


}